import httpClient from "@/lib/http-client";
import {format, fromUnixTime} from 'date-fns';
import {db} from "@/lib/db";
import memoize from "memoize";

export const memoizedThsNews = memoize(async (code) => await getThsNews(code), {maxAge: 5000})

const itemToNews = (item: any) => {
    // console.log(item, item.combination[-1]?.simpleModule?.bottomBar?.time);
    const newsId = item.info?.itemId;
    // const isSimple = item.combination.length === 1;
    let newsTitle = '';
    let tm = 0;
    if (item.combination.length === 1) {
        newsTitle = item.combination[0].simpleModule.title;
        tm = item.combination[0].simpleModule.bottomBar.time;
    }
    if (item.combination.length === 2) {
        newsTitle = item.combination[0].title.content;
        const lastItem = item.combination[item.combination.length - 1];
        tm = lastItem.bottomBar.time;
    }
    if (item.combination.length >= 3) {
        newsTitle =
            item.combination[1]?.htmlAbstract?.content ||
            item.combination[1]?.title?.content ||
            item.combination[0]?.title?.content;
        const lastItem = item.combination[item.combination.length - 1];
        tm = lastItem.bottomBar.time;
    }
    const newsTimeObj = fromUnixTime(tm / 1000);
    const pattern = 'MM-dd HH:mm';
    const newsTime = format(newsTimeObj, pattern);
    // console.log(newsTitle, newsTimeObj, newsTime);
    const newsUrl = item.info?.jumpUrl;
    return {
        newsId,
        newsTitle,
        newsTime,
        newsUrl,
        newsTimeObj
    };
};


export async function getThsNews(code: string) {
    const marketCode = code.startsWith('6') ? '17' : '33';
    const url = `https://m.10jqka.com.cn/app/timeline/v1/list?marketCode=${marketCode}&stockCode=${code}`;
    const resp = await httpClient.get(url);
    const news = resp.pageItems || [];
    // const sortedNews = convtedNews.sort((a, b) => b.newsTime - a.newsTime);
    return news.map((item: any) => itemToNews(item));
}

export async function getThsZjMix() {
    return null
}


// getBlockZjMix().then(resp => console.log(resp))